package com.example.exam.realm;

import com.example.exam.entity.User;
import com.example.exam.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author shishuqian
 * date 2021/5/12
 * time 15:45
 * 自定义shiro过滤器
 **/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将用户信息封装为token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据用户输入的username去数据库查询信息
        User user = userService.findByUsername(token.getUsername());
        if (user != null){
            //将token里的密码和正确密码对比
            //若抛异常，则密码错误
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        //用户名错误
        return null;
    }
}
